package main

import (
    "github.com/gin-contrib/gzip"
    "github.com/gin-gonic/gin"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "path/filepath"
)

type SelfFileInfo struct {
    FileName string
    DateTime string
    FileSize uint64
}

const filePath = "/usr/share/nginx/file"

//const filePath  = "/data/github.com"

var Debug *log.Logger

func getDirList() ([]string, error) {
    var dirList []string
    dirErr := filepath.Walk(filePath,
        func(path string, f os.FileInfo, err error) error {
            if f == nil {
                return err
            }
            if f.IsDir() {
                dirList = append(dirList, path)
                return nil
            }

            return nil
        })
    return dirList, dirErr
}

func WebService() {

    Debug = log.New(os.Stdout, "[debug]", log.Ldate|log.Ltime|log.Lshortfile)
    router := gin.Default()
    router.Use(gzip.Gzip(gzip.DefaultCompression))
    router.LoadHTMLGlob("html_template/*")

    router.GET("/:FileName", func(context *gin.Context) {
        fileName := context.Param("FileName")
        Debug.Println("FileName : ", fileName)

        fullFileName := filepath.Join(filePath, fileName)
        Debug.Println("FileName : ", fileName)
        if _, err := os.Stat(fullFileName); nil != err {
            context.JSON(http.StatusNotFound, gin.H{fileName: "not found"})
        } else {
            //attachment; FileName=[FileName] 对下载的文件重命名
            context.Writer.Header().Add("Content-Disposition", "attachment; FileName="+fileName)
            context.Writer.Header().Add("Content-Type", "application/octet-stream")
            context.File(fullFileName)
        }
    })

    router.GET("/", func(context *gin.Context) {
        files, err := ioutil.ReadDir(filePath)
        mFiles := make([]SelfFileInfo, 1)
        if err == nil {
            length := len(files)
            mFiles = make([]SelfFileInfo, length)

            for _, tFileInfo := range files {
                tFile := SelfFileInfo{
                    FileName: string(tFileInfo.Name()),
                    DateTime: tFileInfo.ModTime().String(),
                    FileSize: uint64(tFileInfo.Size()),
                }
                mFiles[length-1] = tFile
                length--
            }
            //body, err := jsoniter.Marshal(mFiles)
            //if err != nil {
            //    context.JSON(http.StatusBadGateway, gin.H{"error": err})
            //} else {
            //    context.String(http.StatusOK, string(body))
            //    //context.Data(http.StatusOK, "Content-Type:application/json", body)
            //}
        }
        context.HTML(http.StatusOK, "index.tmpl", mFiles)
    })

    err := router.Run(":80")

    if err != nil {
        panic(err)
    }
}

func main() {
    WebService()
}
